#!/usr/bin/env python
# This shebang line specifies that the script should be executed using the python interpreter found in the user's environment.
# Import the os module to interact with the operating system, particularly for accessing environment variables.
import os


# This function is designed to initialize a database. It reads connection details from an environment variable,
# connects to the MySQL server, and creates the specified database if it doesn't already exist.
# @pysnooper.snoop()
def init_db():
    # Retrieve the database connection string from an environment variable named 'MYSQL_SERVICE'.
    # If the environment variable is not set, it defaults to an empty string.
    SQLALCHEMY_DATABASE_URI = os.getenv('MYSQL_SERVICE', '')
    # The following block of code will only execute if a database URI was provided.
    if SQLALCHEMY_DATABASE_URI:
        # Import the 'url' module from SQLAlchemy's engine to help parse the database connection string.
        import sqlalchemy.engine.url as url

        # Parse the connection string into a structured URL object, which makes it easy to access
        # individual components like host, port, username, password, and database name.
        uri = url.make_url(SQLALCHEMY_DATABASE_URI)
        """Inits the Myapp application"""
        # Import the pymysql library, which is a pure-Python MySQL client used to connect to the database.
        import pymysql

        # 创建连接
        # Establish a connection to the MySQL server using the details parsed from the URI.
        # The charset is set to 'utf8' to ensure proper handling of Unicode characters.
        conn = pymysql.connect(
            host=uri.host, port=uri.port, user=uri.username, password=uri.password, charset='utf8'
        )
        # 创建游标
        # Create a cursor object from the connection. The cursor is used to execute SQL commands.
        cursor = conn.cursor()

        # 创建数据库的sql(如果数据库存在就不创建，防止异常)
        # Construct the SQL statement to create the database.
        # 'CREATE DATABASE IF NOT EXISTS' prevents an error if the database already exists.
        # It also sets the default character set and collation for the new database.
        sql = (
            'CREATE DATABASE IF NOT EXISTS %s DEFAULT CHARACTER '
            'SET utf8 DEFAULT COLLATE utf8_general_ci;'
        ) % uri.database
        # 执行创建数据库的sql
        # Execute the prepared SQL statement using the cursor.
        cursor.execute(sql)
        # Commit the transaction to make the database creation permanent.
        conn.commit()


# Call the init_db function to execute the database initialization logic when the script is run.
init_db()
